
package controllers;

import models.Track;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;
import play.Logger;


public class YouTube {

	static String getVideos(Track t) {
		String query = spaceToPlus(t.artist.name + " " + t.name);
		try {
			Document doc = Jsoup.connect("https://gdata.youtube.com/feeds/api/videos?"
					+ "q=" + query
					+ "&key=AI39si67RZsQFxmbAuzciXqbiaJhxxW_7cXhHwDQCbdAZvwpDjDF_gG98bqp49MTHe06DNyFoYSfPp_AW_lC_V5p8xiwHT1E5A")
					.ignoreContentType(true).get();
			Elements entries = doc.select("entry");

			//Logger.warn(result);
			String result = "";
			int count = 0;
			for (Element e : entries) {
				if (e.select("yt|noembed").isEmpty()) {	//embedding not disabled by request
					String ytid = getIdFromUrl(e.select("id").html());
					if (t.blacklist == null || !t.blacklist.contains(ytid)) {
						if (result.equals(""))
							result = ytid;
						else
							result += "&" + ytid;
						if (++count == 4)
							break;
					}
				}
//				Logger.info(e.select("title").html());
//				Logger.info(e.select("content").html());
//				Logger.info(e.select("author name").html());
			}
			return result;
		} catch (Exception e) {
			return "";
		}
	}

	static String getIdFromUrl(String url) {
		return url.substring(url.lastIndexOf('/') + 1);
	}

	static String spaceToPlus(String s) {
		return s.replaceAll("[\\s]+", "+");
	}

	static void saveTrackVideo(Track t) {
		if (t == null)
			return;
		if (t.cache == null || t.cache.equals("")) {
			String vid = getVideos(t);
			t.cache = vid;
			t.save();
		}
	}
}
